package com.faxsun.cms.web.processor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.broadleafcommerce.cms.web.processor.UrlRewriteProcessor;
import org.broadleafcommerce.common.web.BroadleafRequestContext;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.standard.expression.Expression;
import org.thymeleaf.standard.expression.StandardExpressions;

public class FSUrlRewriteProcessor extends UrlRewriteProcessor {

	@Override
	protected Map<String, String> getModifiedAttributeValues(Arguments arguments, Element element,
			String attributeName) {
		Map<String, String> attrs = new HashMap<String, String>();
		HttpServletRequest request = BroadleafRequestContext.getBroadleafRequestContext().getRequest();

		boolean secureRequest = true;

		if (request != null) {
			secureRequest = isRequestSecure(request);
		}

		String elementValue = element.getAttributeValue(attributeName);

		if (elementValue.startsWith("/")) {
			elementValue = "@{ " + elementValue + " }";
		}
		Expression expression = (Expression) StandardExpressions.getExpressionParser(
				arguments.getConfiguration()).parseExpression(arguments.getConfiguration(), arguments,
				elementValue);
		String assetPath = (String) expression.execute(arguments.getConfiguration(), arguments);

		// TODO: It's a bug fix from 4.0.0-GA. Should replace the blc cms to
		// 4.0.0-GA soon and remove this whole class.
		assetPath = staticAssetPathService.convertAssetPath(assetPath, null, secureRequest);

		attrs.put("src", assetPath);

		return attrs;
	}

}
